package com.lkchan.dexfile;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private static String path = "";

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("lkchandexfile");

        try {
            Application app = getApplicationUsingActivityThread();
            path = app.getPackageManager().getApplicationInfo(app.getPackageName(), 0).publicSourceDir;
//            File file = new File(path);
//            if (file.exists() && file.canRead()) {
//                tv.setText(getApkDexInfo(file.getAbsolutePath()));
//            } else {
//                tv.setText("no apk file !!!");
//            }
            init(path);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private native static void init(String path);

    @SuppressLint("PrivateApi")
    private static Application getApplicationUsingActivityThread() throws Exception {
        return (Application) Class.forName("android.app.ActivityThread")
                .getMethod("currentApplication").invoke(null, (Object[]) null);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Example of a call to a native method
        TextView tv = findViewById(R.id.sample_text);
        long startTime = System.currentTimeMillis();
        Object result;

        result = invoke(convertClassToSignature(MainActivity.class), "test", "()Ljava/lang/Object;");
        result = invoke(convertClassToSignature(MainActivity.class), "onCreate", "(Landroid/os/Bundle;)V");
        result = invoke(convertClassToSignature(MainActivity.class), "<init>", "()V");
        result = invoke(convertClassToSignature(MainActivity.class), "<clinit>", "()V");
        long delta = System.currentTimeMillis() - startTime;
        Log.d(TAG, "" + result + " cost: " + delta + " ms");

    }

    private static String convertClassToSignature(Class<?> cls) {
        return "L" + cls.getName().replace('.', '/') + ";";
    }

    @SuppressWarnings("unused")
    private Object test() {
        return "111222";
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String getApkDexInfo(String path);

    public native Object invoke(String className, String methodName, String methodSignature);

}
